package cn.smile.business.log.impl;

import cn.smile.bean.dto.log.LogInfoDTO;
import cn.smile.bean.entity.log.LogInfo;
import cn.smile.bean.form.core.user.QueryUserForm;
import cn.smile.bean.form.log.log.LogAddForm;
import cn.smile.bean.form.log.log.LogQueryForm;
import cn.smile.business.core.ISysUserService;
import cn.smile.business.log.ILogInfoService;
import cn.smile.commons.constant.CommonConstant;
import cn.smile.commons.constant.NumberConstant;
import cn.smile.commons.domain.BaseServiceImpl;
import cn.smile.repository.log.LogInfoMapper;
import cn.smile.utils.BeanCopy;
import cn.smile.utils.DateFormatUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import jakarta.annotation.Resource;
import java.util.*;

/**
 * @author smile-jt
 */
@Slf4j
@Service
public class LoginfoServiceImpl extends BaseServiceImpl<LogInfoMapper, LogInfo> implements ILogInfoService {
    @Resource
    private ISysUserService userService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean addInfo(LogAddForm form) {
        log.info("[LoginfoServiceImpl].[addInfo] ------> 拦截器新增URI访问记录 Start, form = {}", JSON.toJSONString(form));
        LogInfo entity = BeanCopy.copyBean(form, LogInfo.class);
        super.addBaseCol(entity);
        int insertNum = baseMapper.insert(entity);
        log.info("[LoginfoServiceImpl].[addInfo] ------> 拦截器新增URI访问记录 End, insertNum = {}", insertNum);
        return insertNum > NumberConstant.ZERO;
    }

    @Override
    public IPage<LogInfoDTO> queryPage(LogQueryForm form) {
        log.info("[LoginfoServiceImpl].[queryPage] ------> 分页查询拦截器访问记录 Start, form = {}", JSON.toJSONString(form));
        Page<LogInfo> dataPage = baseMapper.selectPage(form.queryPage(), this.getQueryParams(form));
        IPage<LogInfoDTO> result = BeanCopy.copyPage(dataPage, LogInfoDTO.class);
        this.setDetail(result.getRecords());
        log.info("[LoginfoServiceImpl].[queryPage] ------> 分页查询拦截器访问记录 End");
        return result;
    }

    @Override
    public void taskDelInfo(Date endDate) {
        String datetime = DateFormatUtil.parseDateToStr(endDate, DateFormatUtil.DATE_TIME_FORMAT_1);
        log.info("[LoginfoServiceImpl].[taskDelInfo] ------> 删除过期日志 Start, endDate = {}", datetime);
        List<LogInfo> baseList = baseMapper.selectList(new QueryWrapper<LogInfo>().lambda().le(LogInfo::getAccessTime, datetime));
        int delNum = NumberConstant.ZERO;
        if (!CollectionUtils.isEmpty(baseList)) {
            for (LogInfo entity : baseList) {
                delNum += baseMapper.deleteById(entity);
            }
        }
        log.info("[LoginfoServiceImpl].[taskDelInfo] ------> 删除过期日志 End, delNum = {}", delNum);
    }

    /**
     * 获取分页查询参数
     *
     * @param form 查询参数
     * @return 查询对象
     */
    private LambdaQueryWrapper<LogInfo> getQueryParams(LogQueryForm form) {
        LambdaQueryWrapper<LogInfo> qw = new QueryWrapper<LogInfo>().lambda().eq(LogInfo::getDeleted, Boolean.FALSE);
        if (!ObjectUtils.isEmpty(form.getUri())) {
            qw.like(LogInfo::getUri, form.getUri());
        }
        if (!ObjectUtils.isEmpty(form.getIp())) {
            qw.like(LogInfo::getAccessIp, form.getIp());
        }
        if (!ObjectUtils.isEmpty(form.getReject())) {
            qw.eq(LogInfo::getReject, form.getReject());
        }
        if (!ObjectUtils.isEmpty(form.getAccessTimeStart())) {
            qw.ge(LogInfo::getAccessTime, form.getAccessTimeStart());
        }
        if (!ObjectUtils.isEmpty(form.getAccessTimeEnd())) {
            qw.le(LogInfo::getAccessTime, form.getAccessTimeEnd());
        }
        return qw;
    }

    /**
     * 信息补充
     *
     * @param dataList 数据集合
     */
    private void setDetail(List<LogInfoDTO> dataList) {
        if (!CollectionUtils.isEmpty(dataList)) {
            Set<String> userIds = new HashSet<>(NumberConstant.EIGHT);
            dataList.forEach(dto -> userIds.add(dto.getUserId()));
            Map<String, String> userMap = super.getUserMap(userService.queryList(new QueryUserForm().setIds(Lists.newArrayList(userIds))));
            for (LogInfoDTO dto : dataList) {
                dto.setNickName(userMap.getOrDefault(dto.getUserId(), CommonConstant.DEFAULT_NAME_STRING));
            }
        }
    }
}
